package com.aaron.server;

import java.sql.*;
import java.util.ArrayList;
import com.aaron.client.Workspace;
import com.aaron.client.ProjectProxy;

public class WorkspaceServer {
	private Connection con;
	public WorkspaceServer()throws DatabaseException{
		try{
			String username="aaron";
			String password="li!insin";
			String url = "jdbc:mysql://localhost/VivCode";
			Class.forName ("com.mysql.jdbc.Driver").newInstance ();
			con = DriverManager.getConnection (url, username, password);
		}
		catch(ClassNotFoundException e){
			throw new DatabaseException(e.getMessage());
		}
		catch(InstantiationException e){
			throw new DatabaseException(e.getMessage());
		}
		catch(IllegalAccessException e){
			throw new DatabaseException(e.getMessage());
		}
		catch(SQLException e){
			throw new DatabaseException(e.getMessage());
		}
	}
	public Workspace getWorkspace(String username){
		Workspace workspace=new Workspace();
		try{
			String sql="SELECT `name`,`last_editor`,`last_edited`,`path`  FROM `Projects` WHERE `username` = '"+username+"';";
			System.err.println ("getWorkspace: sql="+sql);
			Statement stmt = con.createStatement();
			//if projects found
			ResultSet rs=stmt.executeQuery(sql);
			while(rs.next()){
				String path=rs.getString("path");
				String sql2="SELECT `username`,`association`  FROM `Projects` WHERE `path` = '"+path+"';";
				System.err.println ("getWorkspace: sql="+sql2);
				Statement stmt2 = con.createStatement();
				ResultSet rs2=stmt2.executeQuery(sql2);
				String owner="";
				ArrayList collaborators=new ArrayList();
				ArrayList viewers=new ArrayList();
				System.err.println ("getWorkspace: Project: "+rs.getString("name"));
				while(rs2.next()){
					String association=rs2.getString("association");
					System.err.println ("getWorkspace: Project "+association+": "+rs2.getString("username"));
					
					if(association.equals("owner")){
						owner=rs2.getString("username");
					}
					else if(association.equals("collaborator")){
						collaborators.add(rs2.getString("username"));
					}
					else if(association.equals("viewer")){
						viewers.add(rs2.getString("username"));
					}
					else{
						System.err.println ("getWorkspace: Unknown assoication '"+association+"'.");
					}
				}
				workspace.addProjectProxy(new ProjectProxy(rs.getString("name"), owner, collaborators, viewers, rs.getString("last_editor"), rs.getString("last_edited")));
				System.err.println ("getWorkspace: collaborators: "+collaborators.size());
				System.err.println ("getWorkspace: viewers: "+viewers.size());
			}
		}
		catch(SQLException e){
			System.err.println ("getWorkspace: SQLException: "+e.getMessage());
		}
		return workspace;
	}
}
